package tdd.xuchun.test.util;

import java.io.IOException;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpUtil {

	/*
	 * 访问网页并获得状态码
	 */
	@SuppressWarnings("finally")
	public static int getStateCode(String url) {
		int code = 0;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(1000).build();
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpGet);

			//System.out.println("得到的结果:" + response.getStatusLine());// 得到请求结果
			// String s = EntityUtils.toString(response.getEntity(), "UTF-8");
			// System.out.println(s);
			code = response.getStatusLine().getStatusCode();
		} catch (IOException e) {
			throw e;
		} finally {
			return code;
		}

	}

}
